//
//  UNFloatingView.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/11/14.
//

import UIKit
import RxSwift

public class UNFloatingView: UIView{
    
    // 记录拖动时的起始点
    private var panStartLocation: CGPoint = .zero
    
    var bag: DisposeBag? = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: .init(x: MainWidth - 72, y: MainHeight / 3, width: 72, height: 82))
        
        applyBlurEffect()
        setupView()
        setupPanGesture()
        observeFrameChanges()
        
        setTapGesture()
    }
    
    public func showFloatingView(){
        UIApplication.shared.currentWindow?.addSubview(self)
        
    }
    
    public func hiddenFloatingView(){
        self.removeFromSuperview()
        bag = nil
    }
    
    func setTapGesture(){
        
        // 添加tap手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
        isUserInteractionEnabled = true
        addGestureRecognizer(tapGesture)
        
    }
    
    @objc public func handleTapGesture(){
        
    }
    
    
    private func setupPanGesture() {
        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        addGestureRecognizer(pan)
        isUserInteractionEnabled = true
    }
    
    @objc private func handlePan(_ pan: UIPanGestureRecognizer) {
        guard let superview = self.superview else { return }

        let translation = pan.translation(in: superview)

        switch pan.state {
        case .began:
            panStartLocation = center
        case .changed:
            // 更新中心点，达到拖动效果
            let newCenter = CGPoint(x: panStartLocation.x + translation.x, y: panStartLocation.y + translation.y)
            center = newCenter
        case .ended, .cancelled:
            // 自动贴边
            snapToEdgesIfNeeded()
        default:
            break
        }
    }
    
    /// 自动贴边
    private func snapToEdgesIfNeeded() {
        guard let superview = superview else { return }

        let screenWidth = superview.bounds.width
        // 顶部和底部边界
        let topHeight = StatusHeight
        let bottomHeight = superview.bounds.height - bottomSafeArea - bounds.height

        // 计算当前中心点的 x 值
        var newFrame = frame
        // 限制上边界
        if newFrame.minY < topHeight {
            newFrame.origin.y = topHeight
        }
        // 限制下边界
        if newFrame.minY > bottomHeight {
            newFrame.origin.y = bottomHeight
        }
        
        // 判断是否隐藏到左边
        if newFrame.origin.x < -(bounds.width / 3) {
            newFrame.origin.x = -48
        }else if newFrame.origin.x > screenWidth - (bounds.width / 3)*2 {
            newFrame.origin.x = screenWidth - bounds.width / 3
        }else{
            // 判断是否接近左边或右边
            if newFrame.origin.x < screenWidth / 2 {
                // 贴左边
                newFrame.origin.x = 6
            } else {
                // 贴右边
                newFrame.origin.x = screenWidth - bounds.width - 6
            }
        }
        
        UIView.animate(withDuration: 0.3) {
            self.frame = newFrame
        }
    }
    
    private func setupView() {
        
        dcockedView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(dcockedView)
        NSLayoutConstraint.activate([
            dcockedView.topAnchor.constraint(equalTo: self.topAnchor),
            dcockedView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            dcockedView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            dcockedView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
        ])
        
    }
    
    /// 监听 fame
    func observeFrameChanges() {
        // 使用 rx.observe 监听 frame 属性
        self.rx.observe(CGRect.self, "frame") .subscribe(onNext: { [weak self] newFrame in
            guard let self = self, let frame = newFrame else { return }
            var progress = 0.0
            let width = bounds.size.width / 3 * 2
            if frame.origin.x < 0 {
                progress = abs( frame.origin.x ) / width
            }
            if frame.origin.x > MainWidth - bounds.size.width {
                progress = ( frame.origin.x - (MainWidth - bounds.size.width) ) / width
            }
            progressDidChange(progress)
            dcockedView.alpha = progress
        }) .disposed(by: bag!)
    }
    
    /// 浮窗贴到屏幕边缘的进度
    public func progressDidChange(_ progress: Double){
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var dcockedView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 12
        view.layer.masksToBounds = true
        view.layer.borderWidth = 0.5
        view.layer.borderColor = UIColor.FromHex(rgb: 0x000000, alpha: 0.1).cgColor
        view.backgroundColor = .FromHex(rgb: 0x000000, alpha: 0.1)
        
        let left = UIView()
        left.backgroundColor = .FromHex(rgb: 0xFFFFFF, alpha: 0.8)
        left.layer.cornerRadius = 2
        left.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(left)
        NSLayoutConstraint.activate([
            left.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
            left.topAnchor.constraint(equalTo: view.topAnchor, constant: 21),
            left.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            left.widthAnchor.constraint(equalToConstant: 4)
        ])
        
        let right = UIView()
        right.backgroundColor = .FromHex(rgb: 0xFFFFFF, alpha: 0.8)
        right.layer.cornerRadius = 2
        
        right.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(right)
        NSLayoutConstraint.activate([
            right.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
            right.topAnchor.constraint(equalTo: left.topAnchor),
            right.widthAnchor.constraint(equalTo: left.widthAnchor),
            right.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
        
        return view
    }()
    
}
